#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#include "def.h"

typedef int datatype;

typedef struct kernel{
    int data;
    struct list_head my;
}kernel,*pklist;

pklist creat_head(){
    pklist head = (pklist)malloc(sizeof(kernel));
    if(head == NULL){
        printf("malloc err\n");
        return NULL;
    }
    INIT_LIST_HEAD(&(head->my));
    return head;
}

pklist creat_node(datatype data){
    pklist node=creat_head();
    if(node == NULL){
        printf("create head err\n");
        return NULL;
    }
    node->data=data;
    return node;
}

static void list_add(struct list_head* new,struct list_head* head){
    __list_add(new,head,head->next);
}


void insert_head(pklist head){
    int data =0;
    printf("请输入\n");
    scanf("%d",&data);
    pklist new = creat_node(data);
    if(new == NULL){
        printf("create new err\n");
        return ;
    }
    int true=0;
    struct list_head* pos=NULL;
    pklist node = NULL;
    if((&(head->my))->next == &(head->my)){ //首节点直接插
        list_add(&(new->my),&(head->my));
    }
    else{
        list_for_each(pos,&(head->my)){
            node = list_entry(pos,struct kernel,my);
            if(node->data == data){ //重复则跳出,不插入
                free(new);
                new=NULL;
                return;
            }
            if(data < node->data){      //插在比自己大的前面
                list_add_tail(&(new->my),&(node->my));
                true=1;
                break;
            }
        }
        if(true == 0){  //最大的插最后
            list_add(&(new->my),&(node->my));
        }
    }
    return;
    
}

void show(const pklist head){
    struct list_head* pos=NULL;
    pklist node = NULL;
    list_for_each(pos,&(head->my)){
        node = list_entry(pos,struct kernel,my);
        printf("%d ",node->data);
    }
    printf("\n");

}




int main(void){
    pklist head = creat_head();

    for(int i=0;i<7;i++){
        insert_head(head);
    }
    show(head);

    return 0;
}